import React, { useRef, useState } from 'react';
import { DataService } from '../../API/DataService';
import { useScroll } from '../../hooks/useScroll';
import { ListItem } from './ListItem';

export const List = () => {
  const [todos, setTodos] = useState([]);
  const parentNode = useRef();
  const childrenNode = useRef();
  const [page, setPage] = useState(1);
  const limit = 20;
  const fetchTodos = (limit, page) => {
      DataService.getAll(limit, page)
      .then(res => res)
      .then((json) => {
        setTodos([...todos, ...json]);
        setPage(page + 1);
      });
  };

  useScroll(parentNode, childrenNode, () => {
    fetchTodos(limit, page);
  });

  return (
    <div ref={parentNode} style={{ height: '80vh', overflow: 'auto' }}>
      {todos.map((todo) => (
        <ListItem key={todo.id} todo={todo} />
      ))}
      <div
        ref={childrenNode}
        style={{ height: '20px', backgroundColor: 'green' }}
      ></div>
    </div>
  );
};
